package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.UserPojo;
import com.lei.springbootpractice.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    private final UserService userService;

    @Autowired
    public AdminController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public String userManagement(Model model) {
        List<UserPojo> couriers = userService.getCouriers();
        model.addAttribute("users", couriers != null ? couriers : new ArrayList<>()); // 防止null
        return "admin/user-list";
    }

    @GetMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable("id") String userId) {
        // 添加日志输出
        System.out.println("正在删除用户：" + userId);
        userService.deleteUser(userId);
        return "redirect:/admin/users";
    }
    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        UserPojo user = userService.getUserByUserID(userID);

        // 添加用户总数统计
        int userCount = userService.getCouriers().size();

        model.addAttribute("username", user.getUserName());
        model.addAttribute("userCount", userCount);  // 新增统计值
        return "admin/dashboard";
    }
}